package variabilitysmelldetection.plugin.views;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

import variabilitysmelldetection.WriteCSV;
import variabilitysmelldetection.measurement.models.Project;
import variabilitysmelldetection.plugin.models.ComponentModel;
import variabilitysmelldetection.plugin.models.ItemModel;
import variabilitysmelldetection.plugin.models.OperationModel;


public class MeasuresView extends ViewPart {

	public static final String ID = "variabilitysmelldetection.plugin.views.MeasuresView";

	private TreeViewer viewer;
	private Project project;

	/**
	 * The constructor.
	 */
	public MeasuresView() {}

	/**
	 * Shows the given selection in this view.
	 */
	public void show(Project project, ItemModel itemModels) {
		this.project = project;
		
		viewer.setInput(itemModels);
		viewer.refresh(true);
	}

	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	public void createPartControl(final Composite parent) {
		GridLayout layout = new GridLayout(2, false);
	    parent.setLayout(layout);
	    
		Button saveButton = new Button(parent, SWT.PUSH);
	    saveButton.setText("Save as CSV");
	    saveButton.addSelectionListener(new SelectionAdapter() {
	        @Override
	        public void widgetSelected(SelectionEvent e) {
	        	if (project == null) {
	        		MessageDialog.openInformation(parent.getShell(), "VSD Measures", "Please, select the Measure option in the popup menu before saving the results.");
	        		
	        	} else {
					boolean methodsWritten    = WriteCSV.writeMethods(project);
					boolean componentsWritten = WriteCSV.writeClasses(project);
					boolean projectWritten    = WriteCSV.writeProject(project);
					
					String msg = "The measures' values will be saved in the folder: "+WriteCSV.OUTPUT_FOLDER_NAME+"\n"; 
					msg  += methodsWritten    ? "\nMethods successfully saved"        : "\nError saving methods";
					msg  += componentsWritten ? "\nComponents successfully saved"     : "\nError saving components";
					msg  += projectWritten    ? "\nSPL's measures successfully saved" : "\nError saving SPL's measures";
					
        			MessageDialog.openInformation(parent.getShell(), "VSD Measures", msg);
					
	        	}
	        }
	    }); 
	    GridData gridData = new GridData();
		gridData.horizontalSpan = 2;
		gridData.horizontalAlignment = GridData.END;
		saveButton.setLayoutData(gridData);
	    
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		viewer.getTree().setLinesVisible(true);
		viewer.getTree().setHeaderVisible(true);

		TreeViewerColumn column = new TreeViewerColumn(viewer, SWT.NONE);
		column.getColumn().setWidth(250);
		column.getColumn().setMoveable(true);
		column.getColumn().setText("Measure");
		column.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				return element.toString();
			}
		});
		
		column = new TreeViewerColumn(viewer, SWT.NONE);
		column.getColumn().setWidth(100);
		column.getColumn().setMoveable(true);
		column.getColumn().setText("Refinement?");
		column.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				if (element instanceof ComponentModel) {
					return ((ComponentModel)element).isRefinement() ? "Y" : "N";
				} else if (element instanceof OperationModel) {
					return ((OperationModel)element).isRefinement() ? "Y" : "N";
				}
				return "";
			}
		});

		column = new TreeViewerColumn(viewer, SWT.NONE);
		column.getColumn().setWidth(100);
		column.getColumn().setMoveable(true);
		column.getColumn().setText("Value");
		column.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				if (element instanceof ItemModel) {
					ItemModel itemModel = (ItemModel)element;
					return Double.toString(itemModel.getValue());
				}
				return "";
			}
		});

		viewer.setContentProvider(new MyContentProvider());
		
		// define layout for the viewer
		gridData = new GridData();
		gridData.verticalAlignment = GridData.FILL;
		gridData.horizontalSpan = 2;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.horizontalAlignment = GridData.FILL;
		viewer.getControl().setLayoutData(gridData);

	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}

	private class MyContentProvider implements ITreeContentProvider {
		public void dispose() {}
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {}

		public Object[] getChildren(Object parentElement) {
			return getElements(parentElement);
		}

		public Object[] getElements(Object inputElement) {
			return ((ItemModel) inputElement).getChildren().toArray();
		}

		public Object getParent(Object element) {
			if (element == null) {
				return null;
			}
			return ((ItemModel) element).getParent();
		}

		public boolean hasChildren(Object element) {
			return ((ItemModel) element).getChildren().size() > 0;
		}
	}
}